package swing;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Computer extends JFrame implements ActionListener{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField tf;
	private JButton clear;

	public Computer() {
		setTitle("简易计算器");
				setSize(400, 400);
				setVisible(true);
				setLocation(500,500);
				setDefaultCloseOperation(EXIT_ON_CLOSE);
				JPanel top=new JPanel();
				JPanel center=new JPanel();
				add(top,BorderLayout.NORTH);
				add(center);
				top.setLayout(new BorderLayout());
				tf=new JTextField();
				clear=new JButton("清除");
				clear.addActionListener(this);
				top.add(tf);
				top.add(clear,BorderLayout.EAST);
				String[] str={"7","8","9","+",
						      "4","5","6","-",
						      "1","2","3","*",
						      "0",".","=","/"};
				center.setLayout(new GridLayout(4, 4));
				for(int i=0;i<str.length;i++){
					JButton bt=new JButton(str[i]);
					bt.addActionListener(this);
					center.add(bt);
				}
				
	}
	
	public static void main(String[] args) {
  
		SwingUtilities.invokeLater(new Runnable() {
			
			@Override
			public void run() {
				new Computer();
			}
		});
		
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String cmd=e.getActionCommand();
		if(cmd.equals("清除")){
			tf.setText("");
		}
		else if(".0123456789".indexOf(cmd)>=0){
			String text=tf.getText();
			tf.setText(text+cmd);
		}
		
		
	}
	}


	
